package com.wondertek.poms.service.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wondertek.poms.common.utils.StringUtil;
import com.wondertek.poms.common.vo.GlobalCodeEnum;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.config.UrlConfig;
import com.wondertek.poms.core.service.IContentService;
import com.wondertek.poms.core.service.IPrdContService;
import com.wondertek.poms.dao.po.Content;
import com.wondertek.poms.dao.po.PrdCont;
import com.wondertek.poms.service.vo.PomsInnerVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;


/**
 * @author gaozhengxing gaozhenghang@wondertek.com.cn
 * @date 2021/1/4 14:30
 * @description TODO
 */
@Api(value = "PomsInnerController", description = "调老poms接口")
@RestController
@RequestMapping(value="/poms-inner")
@Slf4j
public class PomsInnerController {

    @Resource
    private RestTemplate restTemplateOut;
    @Autowired
    private IPrdContService prdContService;
    @Autowired
    private IContentService contentService;
    @Autowired
    private UrlConfig urlConfig;

    @PostMapping(value = "/publish-prd-cont")
    public ResultBean publishPrdContent(@RequestBody PomsInnerVo vo) {
        try {
            log.info("url:"+urlConfig.getOnlineUrl()+vo);
            String [] ids=vo.getPrdContIds().split(",");
            StringBuffer sbf=new StringBuffer();
            for (String id:ids) {
                PrdCont prdCont=prdContService.getPrdContByPrdContId(Long.parseLong(id));
                if(prdCont!=null){
                    Content cont=contentService.findByContentId(prdCont.getContentId());
                    if(!onlineTimeIsUp(vo.getType(),cont.getOnlineTime())){
                        return ResultBean.error("节目"+id+"未到上线时间,不能发布!");
                    }
                }
                int bcStatus= prdCont==null?0:prdCont.getBcStatus();
                //1:播控通过
                if(1!=bcStatus){
                    sbf.append(id+",");
                }
            }
            String prdContIds=sbf.toString();
            if(StringUtils.isNotBlank(prdContIds)){
                return ResultBean.error("节目"+prdContIds.substring(0,prdContIds.length()-1)+"播控未通过,不能发布!");
            }
            ResponseEntity<String> responseEntity = restTemplateOut
                    .getForEntity(urlConfig.getOnlineUrl()+ "?prdContIds=" + vo.getPrdContIds()+"&type="+vo.getType(), String.class);
            String result = responseEntity.getBody();
            JSONObject json=JSON.parseObject(result);
            if("true".equals(StringUtil.nullToString(json.get("success")))){
                return new ResultBean(GlobalCodeEnum.SUCCESS.getCode(), "调用成功,请等待后台处理");
            }else{
                log.error(StringUtil.nullToString(json.get("message")));
                return ResultBean.error(StringUtil.nullToString(json.get("message")));
            }
        } catch (Exception e) {
            log.error(e.toString());
            return ResultBean.error(e.toString());
        }
    }

    //到上线时间
    public boolean onlineTimeIsUp(String type,String onlineTime){
        //发布新  -1:提前审核发布
        if(!"-1".equals(type) && StringUtils.isNotBlank(onlineTime)){
            //上线时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date time = sdf.parse(onlineTime);
                long online=time.getTime();
                long now=System.currentTimeMillis();
                //未到上线时间
                if(now<=online){
                    return false;
                }
            }catch (ParseException e){
                log.info("judgeOnlineTime_Exception"+e);
            }
        }
        return true;
    }

    @PostMapping(value = "/recall-prd-cont")
    public ResultBean recallPrdContent(@RequestBody PomsInnerVo vo) {

        try{
            log.info("url:"+urlConfig.getRecallUrl()+vo);
            String [] ids=vo.getPrdContIds().split(",");
            StringBuffer sbf=new StringBuffer();
            for (String id:ids) {
               Integer newPubStatus= prdContService.findNewPubStatusByPrdContId(Long.parseLong(id));
               //12:已发布
               if(12!=newPubStatus){
                   sbf.append(id+",");
               }
            }
            String prdContIds=sbf.toString();
            if(StringUtils.isNotBlank(prdContIds)){
                return ResultBean.error("节目"+prdContIds.substring(0,prdContIds.length()-1)+"未发布成功,不能撤回!");
            }
            ResponseEntity<String> responseEntity = restTemplateOut
                    .getForEntity(urlConfig.getRecallUrl()+ "?prdContIds=" + vo.getPrdContIds(), String.class);
            String result = responseEntity.getBody();
            JSONObject json=JSON.parseObject(result);
            if("true".equals(StringUtil.nullToString(json.get("success")))){
                return new ResultBean(GlobalCodeEnum.SUCCESS.getCode(), "调用成功,请等待后台处理");
            }else{
                log.error(StringUtil.nullToString(json.get("message")));
                return ResultBean.error(StringUtil.nullToString(json.get("message")));
            }
        } catch (Exception e) {
            log.error(e.toString());
            return ResultBean.error(e.toString());
        }
    }

    @PostMapping(value = "/offline-prd-cont")
    public ResultBean offlinePrdCont(@RequestBody PomsInnerVo vo) {
        try{
            log.info("url:"+urlConfig.getOfflineUrl()+vo);
            ResponseEntity<String> responseEntity = restTemplateOut
                    .getForEntity(urlConfig.getOfflineUrl()+ "?prdContIds=" + vo.getPrdContIds(), String.class);
            String result = responseEntity.getBody();
            JSONObject json=JSON.parseObject(result);
            if("true".equals(StringUtil.nullToString(json.get("success")))){
                return new ResultBean(GlobalCodeEnum.SUCCESS.getCode(), "调用成功,请等待后台处理");
            }else{
                log.error(StringUtil.nullToString(json.get("message")));
                return ResultBean.error(StringUtil.nullToString(json.get("message")));
            }
        } catch (Exception e) {
            log.error(e.toString());
            return ResultBean.error(e.toString());
        }
    }

    @PostMapping(value = "/delete-prd-cont")
    public ResultBean deletePrdContent (@RequestBody PomsInnerVo vo){
        try {
            log.info("url:"+urlConfig.getDeleteUrl()+vo);
            String [] ids=vo.getPrdContIds().split(",");
            StringBuffer sbf=new StringBuffer();
            for (String id:ids) {
                Integer newPubStatus= prdContService.findNewPubStatusByPrdContId(Long.parseLong(id));
                //10:待发布,11:发布中,12:已发布
                if(10==newPubStatus || 11==newPubStatus || 12==newPubStatus){
                    sbf.append(id+",");
                }
            }
            String prdContIds=sbf.toString();
            if(StringUtils.isNotBlank(prdContIds)){
                return ResultBean.error("节目"+prdContIds.substring(0,prdContIds.length()-1)+"状态为“待发布”或”发布中“或“已发布”,不能删除!");
            }
            ResponseEntity<String> responseEntity = restTemplateOut
                    .getForEntity(urlConfig.getDeleteUrl()+ "?ids=" + vo.getPrdContIds(), String.class);
            String result = responseEntity.getBody();
            JSONObject json=JSON.parseObject(result);
            if("true".equals(StringUtil.nullToString(json.get("success")))){
                return new ResultBean(GlobalCodeEnum.SUCCESS.getCode(), "调用成功,请等待后台处理");
            }else{
                log.error(StringUtil.nullToString(json.get("message")));
                return ResultBean.error(StringUtil.nullToString(json.get("message")));
            }
        } catch (Exception e) {
            log.error(e.toString());
            return ResultBean.error(e.toString());
        }
    }

    @PostMapping(value = "/reset-prd-cont")
    public ResultBean resetPrdContent (@RequestBody PomsInnerVo vo){
        try {
            log.info("url:"+urlConfig.getDeleteUrl()+vo);
            String [] ids=vo.getPrdContIds().split(",");
            StringBuffer sbf=new StringBuffer();
            for (String id:ids) {
                Integer newPubStatus= prdContService.findNewPubStatusByPrdContId(Long.parseLong(id));
                //22:已撤回
                if(22!=newPubStatus){
                    sbf.append(id+",");
                }
            }
            String prdContIds=sbf.toString();
            if(StringUtils.isNotBlank(prdContIds)){
                return ResultBean.error("节目"+prdContIds.substring(0,prdContIds.length()-1)+"不是已撤回状态,不能重置发布!");
            }
            ResponseEntity<String> responseEntity = restTemplateOut
                    .getForEntity(urlConfig.getResetUrl()+ "?prdContIds=" + vo.getPrdContIds(), String.class);
            String result = responseEntity.getBody();
            JSONObject json=JSON.parseObject(result);
            if("true".equals(StringUtil.nullToString(json.get("success")))){
                return new ResultBean(GlobalCodeEnum.SUCCESS.getCode(), "调用成功,请等待后台处理");
            }else{
                log.error(StringUtil.nullToString(json.get("message")));
                return ResultBean.error(StringUtil.nullToString(json.get("message")));
            }
        } catch (Exception e) {
            log.error(e.toString());
            return ResultBean.error(e.toString());
        }
    }

}
